﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;

namespace ExBug
{
    public partial class ALFrm : FrmWorkspace
    {
        public Boolean AddMode = false;
        private String ContAL = String.Empty;
        private Int32 _idAB = -1;
        public Int32 IDABGenerare
        {
            get
            {
                return _idAB;
            }
            set
            {
                _idAB = value;
                Adauga(this, null);
            }
        }
        private Int16 AnulCurent = 0;
        private Int16 LunaCurenta = 0;
        private String SerieNumerica = String.Empty;
        private int NoRecAdd = 0;
        private List<BindingSource> listBS = new List<BindingSource>();
        private List<SqlDataAdapter> listTA = new List<SqlDataAdapter>();



        public ALFrm(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            workConnString = mInfo.workConnectionString;
            this.HandleAfterAdd += new AfterAddHandler(PACFrm_HandleAfterAdd);
            this.HandleTiparire += new EventHandler(PACFrm_HandleTiparire);
            eSRPDataSet.AngajamentLegal.DataColumn.DefaultValue = DateTime.Now;
            eSRPDataSet.AngajamentLegal.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.AngajamentLegal.SumaTotalaColumn.DefaultValue = 0;

            ALDetaliuDGV.m_AutoCompletionColumns.Add(artAlColumn);
            ALDetaliuDGV.m_AutoCompletionColumns.Add(capitolColumn);
            angajamentLegalTableAdapter.Adapter.RowUpdated += new SqlRowUpdatedEventHandler(Adapter_RowUpdated);
            dataDTP.Format = DateTimePickerFormat.Custom;
            dataDTP.CustomFormat = "dd.MM.yyyy";
        }

        void Adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataRow row in
                    eSRPDataSet.AngajamentLegalDetaliu.Select("IDAL=" + e.Row["IDAL", DataRowVersion.Original].ToString(),
                        "IDAL", DataViewRowState.Added))
                {
                    row["IDAL"] = e.Row["IDAL"];
                }
            }
        }

        void PACFrm_HandleTiparire(object sender, EventArgs e)
        {
        }

        void PACFrm_HandleAfterAdd(object sender, DataGridViewCellEventArgs args)
        {
            String valnew = "1";
            Object ret = null;
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));

            if (SerieNumerica != String.Empty)
            {
                cmd.CommandText = "SELECT [UltimulNrFolosit] FROM [SeriiNumerice] WHERE IDSerie='" + SerieNumerica + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                ret = cmd.ExecuteScalar();
                if (ret != null && ret != DBNull.Value)
                {
                    valnew = ret.ToString();
                }
            }
            ///incrementarea seriei se face la salvare
            ///
            if (NoRecAdd > 0)
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "ActSeriiNumerice";
                if (SerieNumerica != String.Empty)
                {

                    cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumerica));
                    cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                    cmd.ExecuteNonQuery();
                }
                NoRecAdd--;
            }
            else
                NoRecAdd++;
 
            ActiveControl = numarTB;
            /// seteaza valorile din angajament bugetar
            if (_idAB != -1)
            {
                ///daca este ab generat nu se poate modifica pac-ul care sta la baza
                iDABCB.Enabled = false;
                int index = angajamentBugetarBindingSource.Find("IDAB", _idAB);
                if (index < 0)
                {
                    MessageBox.Show("Angajamentul Bugetar cu numarul " + _idAB.ToString() + " - nu se mai gaseste in baza de date!\n Va rugam reincercati generarea lui!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                }
                else
                {
                    angajamentBugetarBindingSource.Position = index;
                    ESRPDataSet.AngajamentBugetarRow dr = ((DataRowView)angajamentBugetarBindingSource.Current).Row
                        as ESRPDataSet.AngajamentBugetarRow;
                    ESRPDataSet.AngajamentLegalRow drAL = ((DataRowView)angajamentLegalBindingSource.Current).Row
                        as ESRPDataSet.AngajamentLegalRow;
                    
                    dataDTP.Value = dr.Data;
                    documenteTB.Text = dr.Compartiment;
                    iDABCB.SelectedValue = dr.IDPAC;
                    sumaTB.Text = dr.SumaTotala.ToString();
                    ///adauga detaliile
                    ///
                    for (Int16 i = 0; i < fKABDetaliuABBindingSource.Count; i++)
                    {
                        ESRPDataSet.AngajamentBugetarDetaliuRow drDet = ((DataRowView)fKABDetaliuABBindingSource.Current).Row
                            as ESRPDataSet.AngajamentBugetarDetaliuRow;
                        fKAngajamentLegalDetaliuAngajamentLegalBindingSource.AddNew();
                        ESRPDataSet.AngajamentLegalDetaliuRow drALDet = ((DataRowView)fKAngajamentLegalDetaliuAngajamentLegalBindingSource.Current).Row
                            as ESRPDataSet.AngajamentLegalDetaliuRow;
                        drALDet.IDAL = drAL.IDAB;
                        drALDet.ArtAl = drDet.ArtAl;
                        drALDet.IDJurnal = drDet.IDJurnal;
                        drALDet.Suma = drDet.Suma;
                        fKABDetaliuABBindingSource.EndEdit();
                        fKPACDetaliuPACBindingSource.MoveNext();
                    }
                        
                    

                }
            }
            this.numarTB.Text = valnew;
            InchideConexiune(cmd.Connection);
        }

        /// <summary>
        /// citeste setarile din ResUmaSetup
        /// </summary>
        /// <param name="sqlConn"></param>
        private void LoadSetup(SqlConnection sqlConn)
        {
            Object ret = GetSetupValue("ExBugSetup", "AnulCurent", ModuleInfo.CodUnitate, sqlConn);
            /// nu a fost configurat modulul
            /// 
            while (ret == null)
            {
                MessageBox.Show("Modulul Executie Bugetara nu a fost configurat. \nVa rugam sa-l configurati!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                ExBugSetupFrm frm = new ExBugSetupFrm(ModuleInfo);
                frm.ShowDialog();
                ret = GetSetupValue("ExBugSetup", "AnulCurent", ModuleInfo.CodUnitate, sqlConn);
            }
            AnulCurent = (Int16)ret;
            ret = GetSetupValue("ExBugSetup", "LunaCurenta", ModuleInfo.CodUnitate, sqlConn);
            LunaCurenta = (Int16)ret;

            SetInfoLunaAnul(LunaCurenta.ToString() + "," + AnulCurent.ToString());
            Object retObj = GetSetupValue("ExBugSetup", "IdSerieAL", ModuleInfo.CodUnitate, sqlConn);
            if (retObj != null && retObj != DBNull.Value)
                SerieNumerica = retObj.ToString();

            retObj = GetSetupValue("ExBugSetup", "ContAL", ModuleInfo.CodUnitate, sqlConn);
            if (retObj != null && retObj != DBNull.Value)
                ContAL = retObj.ToString();
            else
            {
                MessageBox.Show("Modulul Executie Bugetara nu a fost configurat corect. \nVa rugam sa specificati contul de angajamente legale!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                ExBugSetupFrm frm = new ExBugSetupFrm(ModuleInfo);
                frm.ShowDialog();
                ContAL = GetSetupValue("ExBugSetup", "ContAL", ModuleInfo.CodUnitate, sqlConn).ToString();
            }

            SqlCommand cmd = new SqlCommand("select TOP 1 [IDJurnal] from [Jurnale] where [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [Terminal]=1", sqlConn);
            ret = cmd.ExecuteScalar();
            if (ret != null)
            {
                eSRPDataSet.AngajamentLegalDetaliu.IDJurnalColumn.DefaultValue = Convert.ToInt32(ret);
            }
            cmd.CommandText = "select TOP 1 [ArtAl] from [ArticoleAliniate] where [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + "  AND [Terminal]=1";
            ret = cmd.ExecuteScalar();
            if (ret != null)
            {
                eSRPDataSet.AngajamentLegalDetaliu.ArtAlColumn.DefaultValue = ret.ToString();
            }
            

            //ret = GetSetupValue("ResUmaSetup", "Contracte", ModuleInfo.CodUnitate, sqlConn);
            //FolosesteContracte = Convert.ToInt16(ret) != 0;


        }

        private void ALFrm_Load(object sender, EventArgs e)
        {

            SqlConnection con = DeschideConexiune(workConnString);
            try
            {
                jurnaleTableAdapter.Connection = con;
                jurnaleTableAdapter.Fill(eSRPDataSet.Jurnale,ModuleInfo.CodUnitate);
                this.propunereAngajareCheltuialaDetaliuTableAdapter.Connection = con;
                this.propunereAngajareCheltuialaDetaliuTableAdapter.Fill(this.eSRPDataSet.PropunereAngajareCheltuialaDetaliu);
                propunereAngajareCheltuialaTableAdapter.Connection = con;
                propunereAngajareCheltuialaTableAdapter.Fill(this.eSRPDataSet.PropunereAngajareCheltuiala, ModuleInfo.CodUnitate);
                articoleAliniateTableAdapter.Connection = con;
                articoleAliniateTableAdapter.FillByTerminal(eSRPDataSet.ArticoleAliniate, ModuleInfo.CodUnitate);
                this.angajamentBugetarDetaliuTableAdapter.Connection = con;
                this.angajamentBugetarDetaliuTableAdapter.Fill(this.eSRPDataSet.AngajamentBugetarDetaliu);
                this.angajamentBugetarTableAdapter.Connection = con;
                this.angajamentBugetarTableAdapter.Fill(this.eSRPDataSet.AngajamentBugetar, ModuleInfo.CodUnitate);
                this.angajamentLegalDetaliuTableAdapter.Connection = con;
                this.angajamentLegalDetaliuTableAdapter.Fill(this.eSRPDataSet.AngajamentLegalDetaliu);
                this.angajamentLegalTableAdapter.Connection = con;
                this.angajamentLegalTableAdapter.Fill(this.eSRPDataSet.AngajamentLegal,ModuleInfo.CodUnitate);
 
                LoadSetup(con);
                InchideConexiune(con);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return;
            }
            AddBindingSource(angajamentLegalBindingSource);
            AddBindingSource(fKAngajamentLegalDetaliuAngajamentLegalBindingSource);

            listTableAdaptor.Add(angajamentLegalTableAdapter.Adapter);
            listTableAdaptor.Add(angajamentLegalDetaliuTableAdapter.Adapter);

            if (ModuleInfo.CurrentTheme == "tribunal")
            {
                AddButton("Sterge", global::ERPStudio.Properties.Resources.sterge, Sterge, ToolStripItemAlignment.Right, true);
            }
            
            AddButton("Generare OLP", global::ERPStudio.Properties.Resources.diagram, GenerareNC, ToolStripItemAlignment.Right, true);
            HandleSalvare += Salvare; 
            SetTitle();
            if (angajamentLegalBindingSource.Count == 0 || AddMode)
                Adauga(this, null);
        }

        private void GenerareNC(object sender, EventArgs e)
        {
           
        }

        private Decimal GetSum(String numeColoana)
        {
            Decimal total = Decimal.Zero;
            foreach (DataGridViewRow dr in ALDetaliuDGV.Rows)
            {
                if (dr.Cells[numeColoana].Value != DBNull.Value)
                    total += Convert.ToDecimal(dr.Cells[numeColoana].Value);
            }
            return total;
        } 

        override public void Salvare(object sender, EventArgs args)
        {

            MyTrace("Salvare");
            if(ContAL==String.Empty)
            {
                MessageBox.Show("Modulul Executie Bugetara nu a fost configurat corect. \nVa rugam sa specificati contul de angajamente legale!",
                    "Eroare",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Hand);
                return;

            }
            if (angajamentLegalBindingSource.Current!=null &&
                (fKAngajamentLegalDetaliuAngajamentLegalBindingSource.Count == 0))
            {
                MessageBox.Show("Este obligatorie adaugarea unei sume pe clasificatiile economice si bugetara!",
                      "Eroare",
                      MessageBoxButtons.OK,
                      MessageBoxIcon.Information);
                return;
            }
            base.Salvare(this, args);
            if (EroareSalvare)
                return;

            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "GenNotaAL";
            cmd.Parameters.Add(new SqlParameter("@IDAL",((ESRPDataSet.AngajamentLegalRow)((DataRowView)angajamentLegalBindingSource.Current).Row).IDAL));
            try
            {
                if(NoRecUpdated!=0)
                    cmd.ExecuteNonQuery();

                cmd.CommandText = "ActSeriiNumerice";

                if (SerieNumerica != String.Empty)
                    if (NoRecAdd > 0)
                    {
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumerica));
                        cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                        cmd.ExecuteNonQuery();
                        NoRecAdd = 0;
                    }

            }
            catch(Exception ex)
            {
                MessageBox.Show("Eroare la salvare:" + ex.ToString(),
                      "Eroare",
                      MessageBoxButtons.OK,
                      MessageBoxIcon.Information);
                return;
            }
            finally
            {
                InchideConexiune(cmd.Connection);
            }

            

            String newVal = GetSum("sumaColumn").ToString("N2");
            if (this.sumaTB.Text != newVal)
                this.sumaTB.Text = newVal;
        }

        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {
            ExBugSetupFrm frm = new ExBugSetupFrm(ModuleInfo);
            frm.ShowDialog();
            this.OnActivated(null);
            ///actualizare unitate la copi
            foreach (Form frmChild in this.MdiParent.MdiChildren)
            {
                //if (frmChild != this)
                ((StudioForm)frmChild).SetCurentMonth(ModuleInfo.CodUnitate);
            }
        }

        override public void SetCurentMonth(short vCodUnitate)
        {
            SqlConnection con=DeschideConexiune(workConnString);
            LoadSetup(con);
            InchideConexiune(con);
        }

        private void ABDetaliuDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            MyTrace("rulajeDGV_CellValueChanged " + e.RowIndex.ToString() + ",coloana=" + e.ColumnIndex.ToString());
            if (e.RowIndex == -1)
                return;
            String newVal;

            if (ALDetaliuDGV.Columns["sumaColumn"] != null)
            {
                if (ALDetaliuDGV.Columns["sumaColumn"].Index == e.ColumnIndex)
                {
                    newVal = GetSum("sumaColumn").ToString("N2");
                    if (this.sumaTB.Text != newVal)
                        this.sumaTB.Text = newVal;
                }
            }
        }
        /// <summary>
        /// functie apelata pentru a calcula suma in cazul stergerii unei linii
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        new public void Sterge(object sender, EventArgs args)
        {
            base.Sterge(sender, args);
            String newVal = GetSum("sumaColumn").ToString("N2");
            if (this.sumaTB.Text != newVal)
                this.sumaTB.Text = newVal;

        }
    }
   
}
